#include "cppTutorStackUsingArray.h"

#include <iostream>

 #ifdef WIN32
    #include <process.h> // system command
    #include <stdlib.h>
 #else
    #include <stdlib.h>
 #endif

using namespace std;

CcppTutorStackUsingArray :: CcppTutorStackUsingArray ()
{
}

CcppTutorStackUsingArray :: CcppTutorStackUsingArray (int capacity)
{
    if (capacity <= 0)
    {
        cout << "Stack's capacity must be positive" << endl;
    }
    
    storage = new int[capacity];
    this->capacity = capacity;
    top = -1;
}


CcppTutorStackUsingArray :: ~CcppTutorStackUsingArray ()
{
    delete [] storage;
}

bool CcppTutorStackUsingArray :: isEmpty ()
{
    return (top == -1);
}

int CcppTutorStackUsingArray :: peek ()
{
    if (isEmpty () == true)
    {
        cout << "Stack is empty" << endl;
        return -1;
    }
    return storage[top];
}

int CcppTutorStackUsingArray :: Push (int nElement)
{
    if (top == capacity)
    {
        cout << "Stack's underlying storage is overflow" << endl;
        return -1;
    }
    top ++;
    storage[top] = nElement;
    return 0;
}

int CcppTutorStackUsingArray :: Pop ()
{
    if (isEmpty () == true)
    {
        cout << "Stack is empty" << endl;
        return -1;
    }
    cout << "delete or poppend element is : " << storage [top] << endl;
    top --; // decrement to delete the element
    return 0;
}

int CcppTutorStackUsingArray :: DisplayStack ()
{
    if (isEmpty () == true)
    {
        cout << "Stack is empty" << endl;
        return -1;
    }
        
    for (int i = top; i>=0; i--)
    {
        cout << storage[i] << " ";
    }
    cout << endl;
    return 0;
}

void CcppTutorStackUsingArray :: StackMenu ()
{
    int choice = 0;
    while (true)
    {
        cout << "1)\tPush" << endl;
        cout << "2)\tPop" << endl;
        cout << "3)\tDisplay" << endl;
        cout << "4)\tExit" << endl;

        choice = 0;
        cin >> choice;

        switch (choice)
        {
            case 1:
                cout << "enter en element : ";
                cin >> choice;
                Push (choice);  // save memory by keeping the same variable
                break;

            case 2:
                Pop ();
                break;

            case 3:
                DisplayStack ();
                break;

            case 4:
                exit (0);
                break;

            default:
                cout << "Unsupported operation, Please try again !!!" << endl;
                break;
            };
        }
}
